let express = require('express');//导入模块
let mysql = require('mysql');


let app = express();
let con = mysql.createConnection({
    host: 'localhost',
    user: 'root',
    password: '123456',
    database: 'users'
})

app.use(express.static('./'));
con.connect();

app.all("*", function (req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");
    next(); // 必须写，如果不写，代码不会在往下执行
  });

//  登录
app.use('/zlogin', (req, res) => {
    let {userphone:userphone,
        password:password
    } = req.query;
    console.log(userphone);
    console.log(password);    

    con.query(`SELECT * FROM people WHERE userphone='${userphone}' AND password='${password}'`, (err, data) => {
        // console.log(err);
        // console.log(data);
         
        if (data[0]) {
            res.send({code: true,msg: '登录成功'})
            return
        }
        res.send({code: false,msg: '用户尚未注册，请注册！'})

        // if (!data){
        //     res.send({code: false,msg: '用户尚未注册，请注册！'}) 
        // }
        // res.send({code: true,msg: '登录成功'})

    })
    // res.send('我是login接口');
})

// 注册
app.use('/zhuce', (req, res) => {
    let {userphone,password,} = req.query;
    con.query(`SELECT * FROM people WHERE userphone='${userphone}'`,(err,data)=>{
        console.log(err);
        console.log(data);
        if(!data.length){
            con.query(`INSERT INTO people  VALUES (${null}, '${ userphone }', '${ password }')`,( err,res)=>{
                console.log(err);
                console.log(res);

            });
            res.send({code:true,msg:'注册成功！'});
            return;
        }
        res.send({code:false,msg:'用户已注册！请直接登录'});

    })
})

app.listen(9090, () => {
    console.log('running port 9090');
})






